$(document).ready(function() {
	menuPage.init();

});

var menuPage = {
	listUrl : _webApp + '/system/menu/list',
	saveUrl : _webApp + '/system/menu/save',
	delUrl : _webApp + '/system/menu/delete',
	permissionUrl : _webApp + '/system/permission/getResourcePermission',
	/**
	 * 初始化
	 */
	init : function() {
		this.initGrid();
		this.initSearch();
		this.initEvent();
	},
	/**
	 * 初始化事件
	 */
	initEvent : function() {
		$('.choose-icon-btn').click(function(){
			menuPage.chooseIcon();
		});
		$('ul.fas li').click(function(){
			var icon = $(this).find('i').attr('class').replace('fa ','');
			$('#iconsDialog').dialog("close");
			$('form .fa').attr('class', 'fa '+icon);
			$('form input[name="icon"]').val(icon);
		});
	},
	/**
	 * 初始化用户管理页
	 */
	initGrid : function() {
		this.dataGrid = $('#data_gird').treegrid({
							url : this.listUrl,
							sortName : "position",
							sortOrder : "asc",
							idField : "id",
							treeField : 'name',
							height : autoHeight(),
							nowrap : true,
							// striped:true,//条纹
							rownumbers : true,
							autoRowHeight : false,
							singleSelect : true,
							checkOnSelect : false,
							selectOnCheck : false,
							columns : [ [
									{
										field : 'id',
										title : 'ID',
										sortable : true,
										hidden : true
									},
									{
										field : 'name',
										title : '名称',
										width : 140,
										sortable : true
									},
									{
										field : 'icon',
										title : '图标',
										width : 50,
										align : 'center',
										halign : 'center',
										formatter : function(value, row, index) {
											return '<i class="fa '+value+'"></i>';
										}
									},
									{
										field : 'url',
										title : 'URL',
										width : 200,
										sortable : true
									},
									{
										field : 'permission',
										title : '对应权限',
										width : 220,
										sortable : true
									},
									{
										field : 'position',
										title : '位置',
										width : 45,
										sortable : true
									},
									{
										field : 'status',
										title : '状态',
										width : 45,
										sortable : true,
										formatter : function(value, row, index) {
											var html = value;
											switch (value) {
											case 0:
												html = "不可用";
												break;
											case 1:
												html = "可用";
												break;
											}
											return html;
										}
									},
									{
										field : 'operate',
										title : '操作',
										width : 160,
										align : 'left',
										halign : 'center',
										formatter : function(value, row, index) {
											var html = "";
											if (row.menuType == "PARENT") {
												if (p_update) {
													html += '<a class="operate_btn" href="javascript:menuPage.editParentmenu(\''
															+ row.id
															+ '\');">编辑</a>';
												}
												if (p_delete) {
													html += '<a class="operate_btn" href="javascript:menuPage.del(\''
															+ row.id
															+ '\');">删除</a>';
												}
												if (p_create) {
													html += '<a class="operate_btn" href="javascript:menuPage.addSubmenu(\''
															+ row.id
															+ '\');">新增子菜单</a>';
												}

											} else if (row.menuType == "CHILD") {
												if (p_update) {
													html += '<a class="operate_btn" href="javascript:menuPage.editSubmenu(\''
															+ row.id
															+ '\');">编辑</a>';
												}
												if (p_delete) {
													html += '<a class="operate_btn" href="javascript:menuPage.del(\''
															+ row.id
															+ '\');">删除</a>';
												}

											}

											return html;
										}
									} ] ],
							toolbar : [ {
								text : '新增父菜单',
								iconCls : 'i_add',
								disabled : !p_create,
								handler : function() {
									menuPage.addParentmenu();
								}
							} ],
							onDblClickRow : function(row) {
								menuPage.edit(row);
							},
							onLoadSuccess : function() {
								menuPage.setParentMenuSelect();
								menuPage.setResourcePermission();
							}
						});
		$(window).resize(function() {
			menuPage.dataGrid.treegrid('resize', {
				height : autoHeight(),
			});
		});

	},
	/**
	 * 初始化搜索栏
	 */
	initSearch : function() {
		// 对搜索按钮和单选框绑定点击搜索事件
		$("#search .search_btn,#search input:radio").click(function() {
			menuPage.search();
		});
		// 对搜索栏输入框绑定回车搜索事件
		$("#search input").keydown(function(event) {
			if (event.keyCode == 13) {
				menuPage.search();
			}
		});
	},
	/**
	 * 搜索,初始化搜索方法initSearch在common.js中 注意不要修改方法名称
	 */
	search : function() {
		var searchData = $("#search_form").serializeJson();
		this.dataGrid.treegrid('load', searchData);
	},
	/**
	 * 刷新
	 */
	refresh : function() {
		this.dataGrid.treegrid("reload");
	},
	/**
	 * 新增父菜单
	 */
	addParentmenu : function() {
		$('#parentmenu_dialog form').form('clear');
		$("#parentmenu_dialog form input[name='menuType']").val("PARENT");
		$("#parentmenu_dialog form input[name='status'][value=1]").prop("checked", true);
		$('#parentmenu_dialog .fa').attr('class','fa')
		this.editParentmenuDialog("新增父菜单");
	},

	/**
	 * 编辑父菜单
	 * 
	 * @param id
	 */
	editParentmenu : function(id) {
		var row = this.dataGrid.treegrid('getSelected');
		$('#parentmenu_dialog form').form('load', row);
		$('#parentmenu_dialog .fa').attr('class','fa '+row.icon)
		this.editParentmenuDialog("编辑父菜单");
	},

	editParentmenuDialog : function(title) {
		var $thisDialog = $('#parentmenu_dialog');
		$thisDialog.dialog({
			title : title,
			width : 400,
			modal : true,
			resizable : true,
			buttons : [ {
				text : '确定',
				handler : function() {
					menuPage.ajaxToSave($thisDialog);
				}
			}, {
				text : '取消',
				handler : function() {
					$thisDialog.dialog("close");
				}
			} ]
		});
	},

	/**
	 * 新增加子菜单
	 */
	addSubmenu : function() {
		var row = this.dataGrid.treegrid('getSelected');
		if (row) {
			$("#submenu_dialog form").form("clear");
			$("#submenu_dialog form input[name='menuType']").val("CHILD");
			$('#submenu_dialog form select[name="parentId"]').val(row.id);
			$("#submenu_dialog form input[name='status'][value=1]").prop("checked", true);
			$('#submenu_dialog .fa').attr('class','fa')
			this.editSubmenuDialog("编辑子菜单");
		}

	},
	edit : function(row) {
		if (row.menuType == "PARENT") {
			this.editParentmenu(row.id);
		} else if (row.menuType == "CHILD") {
			this.editSubmenu(row.id);
		}
	},
	/**
	 * 编辑子菜单
	 * 
	 * @param id
	 */
	editSubmenu : function(id) {
		var row = this.dataGrid.treegrid('getSelected');
		if (row) {
			$('#submenu_dialog form').form('load', row);
			$('#submenu_dialog form select[name="parentId"]').val(row._parentId);
			$('#submenu_dialog .fa').attr('class','fa '+row.icon);
			this.editSubmenuDialog("编辑子菜单");
		}
	},
	editSubmenuDialog : function(title) {
		var $thisDialog = $('#submenu_dialog');
		$thisDialog.dialog({
			title : title,
			width : 400,
			modal : true,
			resizable : true,
			buttons : [ {
				text : '确定',
				handler : function(a) {
					menuPage.ajaxToSave($thisDialog);
				}
			}, {
				text : '取消',
				handler : function() {
					$thisDialog.dialog("close");
				}
			} ]
		});
	},
	ajaxToSave : function(dialog) {
		var options = {
			url : this.saveUrl,
			beforeSubmit : this.validate, // 表单元素有效性验证
			success : function(data) {
				if (typeof data == 'object') {
					if (data.result == "success") {
						dialog.dialog("close");
						messagerShow("保存成功");
					} else {
						$.messager.alert("结果", "保存错误");
					}
					menuPage.refresh();
				} else if (typeof data == 'string') {
					if (data.indexOf("用户权限不足") >= 0) {
						$.messager.alert("警告", "用户权限不足");
					}
				}
			}
		};
		$("form", dialog).ajaxSubmit(options);
	},
	/**
	 * 表单元素有效性验证，使用jquery.validate插件
	 * 
	 * @param arr
	 * @param $form
	 * @param options
	 */
	validate : function(arr, $form, options) {
		// jquery.validate插件无及时验证方法，只能通过提交触发
		$form.validate({
			debug : true,
			rules : {
				name : {
					required : true
				},
				parentId : {
					required : true
				},
				url : {
					required : false
				},
				permission : {
					required : false
				}
			}
		});
		$form.submit();
		return $form.valid();
	},
	/**
	 * 删除
	 * 
	 * @param id
	 */
	del : function(id) {
		var row = this.dataGrid.treegrid('getSelected');
		if (row) {
			$.messager.confirm('确认信息？', '确认删除' + row.name, function(r) {
				if (r) {
					menuPage.ajaxToDelte(row.id);
				}
			});
		}

	},
	ajaxToDelte : function(id) {
		var url = this.delUrl;
		$.post(url, {
			id : id
		}, function(data) {
			if (typeof data == 'object') {
				if (data.result == "success") {
					messagerShow("删除成功");
				} else {
					$.messager.alert("结果", "删除错误");
				}
				menuPage.refresh();
			} else if (typeof data == 'string') {
				if (data.indexOf("用户权限不足") >= 0) {
					$.messager.alert("警告", "用户权限不足");
				}
			}
		});
	},
	/**
	 * 设置父菜单select
	 */
	setParentMenuSelect : function() {
		var roots = this.dataGrid.treegrid("getRoots");
		if (roots) {
			$('#submenu_dialog select[name="parentId"]').html('');
			$.each(roots, function(index, node) {
				$('#submenu_dialog select[name="parentId"]').append(
						'<option value="' + node.id + '">' + node.name
								+ '</option>');
			});
		}

	},
	setResourcePermission : function() {
		$.post(this.permissionUrl, function(data) {
			if (data.result == "success") {
				$('#submenu_dialog select[name="permission"]').html('');
				$.each(data.permissions, function(index, node) {
					$('#submenu_dialog select[name="permission"]').append(
							'<option value="' + node + '">' + node
									+ '</option>');
				});
			} else {
				$('#submenu_dialog select[name="permission"]').html(
						'<option value="">数据获取错误</option>');
			}
		}, "json");
	},
	chooseIcon : function() {
		var $thisDialog = $('#iconsDialog');
		$thisDialog.dialog({
			title : '选择图标',
			width : 860,
			height : 420,
			modal : true,
			resizable : true,
			buttons : [ {
				text : '确定',
				handler : function(a) {
					$thisDialog.dialog("close");
				}
			}, {
				text : '取消',
				handler : function() {
					$thisDialog.dialog("close");
				}
			} ]
		});
	},
};